#ifndef GPIOS_H
#define GPIOS_H

#include "ch32fun.h"
#include <stddef.h>

// Use existing pin definitions from ch32v003fun.h
// Available pins for CH32V003J4M6 (SOP8 package):
// PA1, PA2, PC1, PC2, PC4, PD4, PD1 (SWIO - debug), PD5, PD6
//
// ADC-capable pins (support INPUT_ANALOG mode):
// PA1 (ADC Channel 1), PA2 (ADC Channel 0), PC4 (ADC Channel 2), PD4 (ADC Channel 7)
// Non-ADC pins: PC1, PC2, PD1, PD5, PD6

// CH32V003J4M6 Physical Pin Number API (SOP8 package)
// Pin mapping based on physical IC pin numbers:
// Pin 1: PA1/PD6 [URX/UTX_] [ADC1] [OSCI] - ADC Channel 1
// Pin 2: GND
// Pin 3: PA2 [ADC0] [OSCO] - ADC Channel 0  
// Pin 4: VCC
// Pin 5: PC1 [I2C_SDA] [URX_] - No ADC
// Pin 6: PC2 [I2C_SCL] - No ADC
// Pin 7: PC4 [ADC2] - ADC Channel 2
// Pin 8: PD1/PD4/PD5 [UTX/URX_] [ADC7] [SWIO] - ADC Channel 7

#define PIN_1   PA1   // Physical pin 1: PA1/PD6 - ADC Channel 1
#define PIN_3   PA2   // Physical pin 3: PA2 - ADC Channel 0
#define PIN_5   PC1   // Physical pin 5: PC1 - No ADC
#define PIN_6   PC2   // Physical pin 6: PC2 - No ADC  
#define PIN_7   PC4   // Physical pin 7: PC4 - ADC Channel 2
#define PIN_8   PD4   // Physical pin 8: PD1/PD4/PD5 - ADC Channel 7

// Pin modes
#define INPUT          0x00
#define OUTPUT         0x01
#define INPUT_PULLUP   0x02
#define INPUT_PULLDOWN 0x03
#define OUTPUT_OD      0x04  // Open-drain output
#define INPUT_ANALOG   0x05  // Analog input

// Digital levels
#define LOW   0
#define HIGH  1

// ADC channels (use framework definitions)
#define A0  ANALOG_0   // Channel 0
#define A1  ANALOG_1   // Channel 1 
#define A2  ANALOG_2   // Channel 2
#define A7  ANALOG_7   // Channel 7

// Error codes
#define GPIO_OK           0
#define GPIO_ERROR        1
#define GPIO_INVALID_PIN  2
#define GPIO_INVALID_MODE 3
#define GPIO_NO_ADC       4
#define GPIO_NO_PWM       5
#define GPIO_PIN_RESERVED 6

// Pin reservation system for library integration
#define GPIO_RESERVED_I2C_SDA  PC1  // Reserved for I2C libraries
#define GPIO_RESERVED_I2C_SCL  PC2  // Reserved for I2C libraries

// Pin reservation functions
uint8_t reservePin(uint8_t pin, const char* library_name);
uint8_t releasePin(uint8_t pin);
uint8_t isPinReserved(uint8_t pin);
uint8_t isPinReservedBy(uint8_t pin, const char* library_name);

// Helper functions for pin validation
uint8_t isValidPin(uint8_t pin);
uint8_t isADCPin(uint8_t pin);
uint8_t isPWMPin(uint8_t pin);

// Main GPIO functions
void gpio_init(void);
uint8_t pinMode(uint8_t pin, uint8_t mode);          // Returns error code
uint8_t pinModeReserved(uint8_t pin, uint8_t mode, const char* library_name); // Configure reserved pin
uint8_t digitalRead(uint8_t pin);                    // Returns pin state or GPIO_INVALID_PIN
uint8_t digitalWrite(uint8_t pin, uint8_t value);    // Returns error code
uint16_t analogRead(uint8_t pin);                    // Returns ADC value or 0 if invalid
uint8_t analogWrite(uint8_t pin, uint16_t value);    // Returns error code

#endif // GPIOS_H
